package com.lagou.edu.filter;

import com.lagou.edu.feign.UserServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    static List<String> whiteList = new ArrayList<>();

    static {
        whiteList.add("/user/");
        whiteList.add("/code/");
    }

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        String path = uri.getPath();
        for (String s : whiteList) {
            if (path.startsWith(s)) {
                // 合法请求，放行，执行后续的过滤器
                return chain.filter(exchange);
            }
        }
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst("token");
        if (httpCookie != null && httpCookie.getValue() != null && userServiceFeign.info(httpCookie.getValue()) != null) {
            // 合法请求，放行，执行后续的过滤器
            return chain.filter(exchange);
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
